package com.btrh.util;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Common {
    public static final String DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static final String DATE_TIME_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
    /**
     * 获得一个UUID
     * @return String UUID
     */
    public static String getUUID(){
        String uuid = UUID.randomUUID().toString();
        //去掉“-”符号
        return uuid.replaceAll("-", "");
    }

    /**
     * 发送短信到指定手机
     * @param phoneNums
     * @param content
     * @return
     */
    public  static String sendAliSMS(String phoneNums,String content)
    {
        try {
            //content = java.net.URLEncoder.encode(content, "UTF-8");// 用UTF-8编码执行URLEncode
            String _url = PropUtils.getProp("SMSUrl"); //"http://www.lehuo520.cn/a/sms/api/send"; //接口地址
            String _param = "CorpID="+ PropUtils.getProp("username")+"&Pwd="+ PropUtils.getProp("password")+"" + "&Mobile="+phoneNums+"&Content=" + content+ "&Cell=&SendTime=";

            URL url = null;
            String CorpID= PropUtils.getProp("username");//账户名
            String Pwd= PropUtils.getProp("password");//密码
            String send_content= URLEncoder.encode(content.replaceAll("<br/>", " "), "GBK");//发送内容
            url = new URL(_url+"?CorpID="+CorpID+"&Pwd="+Pwd+"&Mobile="+phoneNums+"&Content="+send_content+"&Cell=&SendTime=");
            BufferedReader in = null;
            int inputLine = 0;
            try {
                System.out.println("开始发送短信手机号码为 ："+phoneNums);
                in = new BufferedReader(new InputStreamReader(url.openStream()));
                inputLine = new Integer(in.readLine()).intValue();
            } catch (Exception e) {
                System.out.println("网络异常,发送短信失败！");
                inputLine=-2;
            }
            System.out.println("结束发送短信返回值：  "+inputLine);
            return String.valueOf(inputLine);
        }catch (Exception e){
            e.printStackTrace();
            return  e.getMessage();
        }
    }
    /**
     * 发送短信到指定手机
     * @param phoneNums
     * @param content
     * @return
     */
    public  static String sendSMS(String phoneNums,String content)
    {
        try {
            content = URLEncoder.encode(content, "UTF-8");// 用UTF-8编码执行URLEncode
            String _url = PropUtils.getProp("SMSUrl"); //"http://www.lehuo520.cn/a/sms/api/send"; //接口地址
            String _param = "username="+ PropUtils.getProp("username")+"&password="+ PropUtils.getProp("password")+"" + "&phone="+phoneNums+"&content=" + content+ "&type=1";

            URL url = null;
            HttpURLConnection urlConn = null;
            url = new URL(_url);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestMethod("POST");
            urlConn.setDoOutput(true);
            OutputStream out = urlConn.getOutputStream();
            out.write(_param.getBytes("UTF-8"));
            out.flush();
            out.close();
            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
            StringBuffer sb = new StringBuffer();
            int ch;
            while ((ch = rd.read()) > -1) {
                sb.append((char) ch);
            }
            System.out.println(sb);
            rd.close();
            return  sb.toString();
        }catch (Exception e){
            e.printStackTrace();
            return  e.getMessage();
        }
    }

    /**
     * 解析Json字符串及数组
     * @param source
     * @param map
     * @return
     */
    public static boolean iteraJsonOrArray(String source, Map map){
        if(source.indexOf(":") == -1){
            return true;
        }
        JSONObject fromObject = JSONObject.parseObject(source);
        Iterator keys = fromObject.keySet().iterator();
        while(keys.hasNext()){
            String key = keys.next().toString();
            Object value = fromObject.get(key);
            String val = value.toString();
            if(val.indexOf("[{") == -1){
                //说明不存在数组json即格式为："[{" 开头的数据。可以允许是[10,11,12]的非json数组
                if(val.indexOf(":") == -1||isDate(val)){
                    map.put(key, val);
                }else{
                    iteraJson(val,map);
                }
            }else if(val.indexOf("[{") != -1){
                //说明存在数组json即格式为：[{开头的json数组
                if(val.indexOf("[{") == 0){
                    //说明当前value就是一个json数组
                    //去除[括号
                    String jsons = val.substring(1, val.lastIndexOf("]"));//得到数据格式为：{...},{...},{...}
                    //把上面得到jsons分割成数组
                    //因为数据格式为{name:joker,age:20},{...},{...}，所以不能用逗号分割。否则会变"{name:joker" "age:20}"
                    //使用正则表达式把},{替换成}|{
                    jsons = jsons.replaceAll("\\}\\s?,\\s?\\{", "}|{");
                    String[] split = jsons.split("\\|");
                    List list=new ArrayList();
                    Map tempMap=null;
                    for(int i = 0; i < split.length;i++){
                        tempMap=new HashMap();
                        iteraJsonOrArray(split[i],tempMap);//符合当前递归条件
                        list.add(tempMap);
                    }
                    map.put(key,list);
                }else{
                    //说明value可能是一个json，这个json中任然包含数组。例如：{inner:[{a:1,b:2,c:3}]}
                    iteraJsonOrArray(val,map);//符合当前递归条件
                }
            }

        }

        return false;
    }
    //递归遍历解析方法
    public static boolean iteraJson(String str,Map res){
        //因为json串中不一定有逗号，但是一定有：号，所以这里判断没有则已经value了
        if(str.toString().indexOf(":") == -1){
            return true;
        }
        JSONObject fromObject = JSONObject.parseObject(str);
        Iterator keys = fromObject.keySet().iterator();
        while(keys.hasNext()){
            String key = keys.next().toString();
            Object value = fromObject.get(key);
            if(iteraJson(value.toString(),res)){
                res.put(key, value);
            }
        }
        return false;
    }
    public static boolean isDate(String strDate) {
        Pattern pattern = Pattern
                .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
        Matcher m = pattern.matcher(strDate);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据日期格式转字符串（年月日时分秒）
     * @param date
     * @return
     */
    public static String dateToString(Date date){
        String sdftime = Common.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS;
        SimpleDateFormat sdf = new SimpleDateFormat(sdftime);
        String format = sdf.format(date);
        return format;
    }
    /**
     * 根据日期格式转字符串(年月日)
     * @param date
     * @return
     */
    public static String dateYearToString(Date date){
        String sdftime = Common.DATE_TIME_PATTERN_YYYY_MM_DD;
        SimpleDateFormat sdf = new SimpleDateFormat(sdftime);
        String format = sdf.format(date);
        return format;
    }

    /**
     * 根据当前时间，添加或减去指定的时间量。例如，要从当前日历时间减去 5 天，可以通过调用以下方法做到这一点：
     * add(Calendar.DAY_OF_MONTH, -5)。
     * @param date 指定时间
     * @param num  为时间添加或减去的时间天数
     * @return
     */
    public static Date getBeforeOrAfterDate(Date date, int num) {
        Calendar calendar = Calendar.getInstance();//获取日历
        calendar.setTime(date);//当date的值是当前时间，则可以不用写这段代码。
        calendar.add(Calendar.DATE, num);
        Date d = calendar.getTime();//把日历转换为Date
        return d;
    }

    /**
     * 拆分字符串 根据传入的指定长度拆分
     * @param str
     * @param len
     * @return
     */
    public static List<String> getListStr(String str, int len) {
        List<String> listStr = new ArrayList<>();
        int strLen = str.length();
        int start = 0;
        int num = len;
        String temp = null;
        while (true) {
            try {
                if (num >= strLen) {
                    temp = str.substring(start, strLen);
                } else {
                    temp = str.substring(start, num);
                }
            } catch (Exception e) {
                System.out.println("完毕");
                break;
            }
            if(!(num>strLen)){
                listStr.add(temp);
                start = num;
                num = num + len;
            }else{
                break;
            }
        }
        return listStr;
    }


    //获取当前年月日  格式月份第一天(xxxx-xx-01 00:00:00)
    public static String getStartTime(String startTime){
        Date date = new Date();
        if(startTime == null || "".equals(startTime)){
            //默认当前月份
            startTime = DateUtil.format(date, "yyyy-MM");
            startTime+="-01 00:00:00";
        }
        return startTime;
    }
    //获取指定月份的开始第一天
    public static String getStartTimeZhiDing(String startTime) throws ParseException {
        if(startTime != null || !"".equals(startTime)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Date parse = sdf.parse(startTime);
            //默认当前月份
            startTime = DateUtil.format(parse, "yyyy-MM");
            startTime+="-01 00:00:00";
        }
        return startTime;
    }

    //获取当前年月日  返回格式月份最后一天(xxxx-xx-31 23:59:59)
    public static String getEndTime(String endTime){
        if(endTime == null || "".equals(endTime)){
            Calendar cale = Calendar.getInstance();
            // 获取前月的最后一天
            cale = Calendar.getInstance();
            cale.add(Calendar.MONTH, 1);
            cale.set(Calendar.DAY_OF_MONTH, 0);
            endTime = DateUtil.format(cale.getTime(),"yyyy-MM-dd");
            endTime+=" 23:59:59";
        }
        return endTime;
    }

    //获取指定月份的最后一天
    public static String getLastDayOfMonth(String yearMonth) {
        int year = Integer.parseInt(yearMonth.split("-")[0]);  //年
        int month = Integer.parseInt(yearMonth.split("-")[1]); //月
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, year);
        // 设置月份
        // cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.MONTH, month); //设置当前月的上一个月
        // 获取某月最大天数
        //int lastDay = cal.getActualMaximum(Calendar.DATE);
        int lastDay = cal.getMinimum(Calendar.DATE); //获取月份中的最小值，即第一天
        // 设置日历中月份的最大天数
        //cal.set(Calendar.DAY_OF_MONTH, lastDay);
        cal.set(Calendar.DAY_OF_MONTH, lastDay - 1); //上月的第一天减去1就是当月的最后一天
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(cal.getTime());
        format += " 23:59:59";
        return format;
    }




}
